#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#define NUM 128
#define CMD_NUM 64

int main()
{
  char command[NUM];
  while(1){
    char* argv[CMD_NUM] = {NULL};
    //1. 打印提示符
    command[0] = 0;
    printf("[hql@HAN ~]# ");
    fflush(stdout);
    //2. 获取命令字符串
    fgets(command, NUM, stdin);
    command[strlen(command) - 1] = '\0'; 
    //printf("echo %s\n", command);
    //3. 解析命令字符串
    const char *sep = " ";
    argv[0] = strtok(command, sep);
    int i = 1;
    while(argv[i] = strtok(NULL, sep))
       i++;
   // for(i = 0; argv[i]; i++) {
   //   printf("argv[%d]:%s\n", i, argv[i]);
   // }
    if(!strcmp(argv[0], "cd")) {
      if(argv[1] != NULL) chdir(argv[1]);
      continue;
    }
    if(fork() == 0) {
      int ret = execvp(argv[0], argv);
      if(ret == -1) {
        printf("command not found\n");
      }
      exit(1);
    }
    int status = 0;
    waitpid(-1, &status, 0);
    printf("exit code:%d\n", (status>>8)&0xFF);
  }

  return 0;
}
